package com.web.homework01;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet(urlPatterns = "/checkuser")
public class CheckUser extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        System.out.println("接收到请求");
        String userName = req.getParameter("userName");

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://127.0.0.1:3306/demo";
            Connection conn = DriverManager.getConnection(url, "root", "root");
            PreparedStatement stmt = conn.prepareStatement("select username from users where username = ?");
            stmt.setString(1, userName);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()){
                resp.getWriter().write("此账号已被注册");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}